package com.qianbao.qianbaobusiness.ui.webview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.androidbase.base.BaseActivity;
import com.androidbase.okhttp.StringCallbackWeakReference;
import com.androidbase.utils.AndroidUtils;
import com.androidbase.utils.DisplayUtils;
import com.androidbase.utils.StatusBarHelper;
import com.androidbase.utils.ToastUtils;
import com.baseandroid.utils.JsonUtil;
import com.facebook.stetho.common.LogUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qianbao.mobilecashier.PayResultCallBack;
import com.qianbao.mobilecashier.QBPaySDK;
import com.qianbao.mobilecashier.utils.PayCode;
import com.qianbao.qianbaobusiness.BuildConfig;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.PayResultCallBackBean;
import com.qianbao.qianbaobusiness.ui.support.businessanalysis.switchshop.AnalysisSwitchShopActivity;
import com.qianbao.qianbaobusiness.ui.widget.dialog.ConfirmDialog;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;
import java.util.Map;

import timber.log.Timber;

public class SimpleWebViewActivity extends BaseActivity {

    public static final String WEBVIEW_URL        = "webview_url";
    public static final String WEBVIEW_TITLE      = "webview_title";
    public static final String WEBVIEW_INIT_QBPAY = "webview_qbpay";

    TextView toolbar_title;
    View     toolbar_back;
    protected WebView  webview;
    protected TextView progress;

    protected String                  mUrl;
    protected HashMap<String, String> mWebViewHeader;
    protected String                  mInitTitle;
    private   String                  mSelectMerchantCallBack;
    private   ConfirmDialog           dialog;
    private   boolean                 mInitQBPay;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview_layout;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mInitQBPay) {
            QBPaySDK.getInstance().onResume();
        }
    }

    @Override
    protected void setupView() {
        StatusBarHelper.translateStatusBar(this);
        toolbar_title = findViewById(R.id.toolbar_title);
        toolbar_back = findViewById(R.id.toolbar_back);
        webview = findViewById(R.id.webview);
        progress = findViewById(R.id.progress);

        mUrl = getIntent().getStringExtra(WEBVIEW_URL);
        mInitQBPay = getIntent().getBooleanExtra(WEBVIEW_INIT_QBPAY, false);
        if (mInitQBPay) {
            QBPaySDK.getInstance().initSDK(this);
        }
        mInitTitle = getIntent().getStringExtra(WEBVIEW_TITLE);
        toolbar_title.setText(R.string.webview_startload_title);
        toolbar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webview.canGoBack()) {
                    webview.goBack();
                } else {
                    finish();
                }
            }
        });

        WebSettings webSettings = webview.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        //若加载的html里有JS在执行动画等操作，会造成资源浪费（CPU、电量）在onStop和onResume
        //里分别把 setJavaScriptEnabled()给设置成false和true即可
        webSettings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        //webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面二个的前提。
        //webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        //webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        //设置图片加载
        webSettings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
        //String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        //webSettings.setAppCachePath(cacheDirPath); //设置  Application Caches 缓存目录
        webSettings.setAppCacheEnabled(false);//开启 Application Caches 功能
        //设置WebView是否使用其内置的变焦机制，该机制结合屏幕缩放控件使用，默认是false，不使用内置变焦机制。
        webSettings.setAllowContentAccess(false);
        //设置WebView是否保存表单数据，默认true，保存数据。
        webSettings.setSaveFormData(true);
        //缓存模式如下：
        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
        if (AndroidUtils.isNetworkAvailable()) {
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        }
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        mWebViewHeader = new HashMap<>();
        mWebViewHeader.put("platform", "Android");
        mWebViewHeader.put("version", BuildConfig.VERSION_CODE + "");
        //mWebViewHeader.put("token", Global.getUserToken());
        //mWebViewHeader.put("channel", AppUtils.getChannel());
        mWebViewHeader.put("Custom-Agent", Build.MODEL + ";" + Build.VERSION.SDK_INT + ";" + BuildConfig.APPLICATION_ID + ";" + BuildConfig.VERSION_CODE + ";" + BuildConfig.VERSION_NAME);

        webview.setWebChromeClient(mWebChromeClient);
        webview.setWebViewClient(mWebViewClient);

        provideHeader();

        webview.loadUrl(mUrl, mWebViewHeader);
        //webview.loadData(htmlData, HtmlUtil.MIME_TYPE, HtmlUtil.ENCODING);
    }

    protected void provideHeader() {

    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        //初始化网络访问
        SimpleOkhttpUtils.getInstance().init(SimpleWebViewActivity.this);
    }

    //辅助WebView处理Javascript的对话框,网站图标,网站标题等
    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        private String mTitle;

        //获取Web页中的标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            this.mTitle = title;
            toolbar_title.setText(mTitle);
        }

        //获得网页的加载进度并显示
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (!isFinishing()) {
                if (newProgress < 99) {
                    toolbar_title.setText(getResources().getString(R.string.webview_startload_title));
                } else {
                    toolbar_title.setText(mTitle);
                }

                if (newProgress == 100) {
                    progress.setVisibility(View.GONE);
                } else {
                    progress.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams lp = progress.getLayoutParams();
                    lp.width = DisplayUtils.getWidth() * newProgress / 100;
                }
            }
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {

        //复写shouldOverrideUrlLoading()方法，使得打开网页时不调用系统浏览器，
        //而是在本WebView中显示
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Timber.e("url = " + url);
            if (url.contains("qianbao://")) {
                //enable js
                goJsEnableQB();
                Uri uriparse = Uri.parse(url);
                if (url.contains("qianbao://requset")) {
                    String httpurl = uriparse.getQueryParameter("url");
                    String httpmethod = uriparse.getQueryParameter("method");
                    String httpbody = uriparse.getQueryParameter("body");
                    String callbackMethod = uriparse.getQueryParameter("callback");
                    requestHttpMethod(httpurl, httpmethod, httpbody, callbackMethod);
                } else if (url.contains("qianbao://closeWeb")) {
                    // 此处不需要再次出来,使用webview自带
                    // finish();
                } else if (url.contains("qianbao://gotoNative")) {
                    String callbackMethod = uriparse.getQueryParameter("callback");
                    String page = uriparse.getQueryParameter("page");
                    if (page.equals("selectMerchant")) {
                        selectMerchant(callbackMethod);
                    }
                }
                if (url.contains("qianbao://riseCasher")) {
                    String cashierId = uriparse.getQueryParameter("cashierId");
                    String cashierToken = uriparse.getQueryParameter("cashierToken");
                    String cashierEnv = uriparse.getQueryParameter("cashierEnv");
                    String callback = uriparse.getQueryParameter("callback");
                    if (mInitQBPay) {
                        showPaySdk(cashierId, cashierToken, cashierEnv, callback);
                    }
                }
                return true;
            }
            if (url.contains("tel")) {
                callPhone(url);
                return true;
            }

            view.loadUrl(url, mWebViewHeader);
            return true;
        }

        //开始载入页面调用的
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        //在页面加载结束时调用
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        //在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
            //handler.cancel(); 默认的处理方式，WebView变成空白页
            //接受证书
            sslErrorHandler.proceed();
            //handleMessage(Message msg); 其他处理
        }

        //加载页面的服务器出现错误时（如404）调用
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            webview.setVisibility(View.GONE);
            //mEmptyView.setVisibility(View.VISIBLE);
            toolbar_title.postDelayed(new Runnable() {
                @Override
                public void run() {
                    toolbar_title.setText(mInitTitle);
                }
            }, 200);
        }

    };

    private void requestHttpMethod(String url, String method, String body, final String callbackMethod) {
        if (method.equalsIgnoreCase("get")) {
            Map<String, String> hashMap = new Gson().fromJson(body, new TypeToken<HashMap<String, String>>() {
            }.getType());
            SimpleOkhttpUtils.get(url)
                    .queries(hashMap)
                    .execute(new StringCallbackWeakReference(webview) {
                        @Override
                        public void handleHttpRespone(String response) {
                            goJsResultCallbackHttp(callbackMethod, 1, response);
                        }

                        @Override
                        public boolean handleException(Throwable throwable) {
                            goJsResultCallbackHttp(callbackMethod, 0, "{errMsg:'错误了'}");
                            return super.handleException(throwable);
                        }
                    });

        } else if (method.equalsIgnoreCase("post")) {
            Map<String, String> hashMap = new Gson().fromJson(body, new TypeToken<HashMap<String, String>>() {
            }.getType());
            if (hashMap.size() == 0) {
                hashMap.put("xxx", "xxx");
            }
            SimpleOkhttpUtils.post(url)
                    .forms(hashMap)
                    .execute(new StringCallbackWeakReference(webview) {
                        @Override
                        public void handleHttpRespone(String response) {
                            goJsResultCallbackHttp(callbackMethod, 1, response);
                        }

                        @Override
                        public boolean handleException(Throwable throwable) {
                            goJsResultCallbackHttp(callbackMethod, 0, "{errMsg:'错误了'}");
                            return super.handleException(throwable);
                        }
                    });
        }
    }

    private void selectMerchant(String callbackMethod) {
        mSelectMerchantCallBack = callbackMethod;
        Intent switchShopIntent = new Intent(this, AnalysisSwitchShopActivity.class);
        startActivity(switchShopIntent);
    }

    public void goJsResultCallbackHttp(String callbackname, int resultCode, String json) {
        exec("javascript:" + callbackname + "(" + resultCode + ", " + json + ");");
    }

    public void goJsGoBackQB() {
        exec("javascript:enableQB();");
        exec("javascript:qbGoBack();");
    }

    public void goJsEnableQB() {
        exec("javascript:enableQB();");
    }

    private void exec(final String trigger) {
        if (Build.VERSION.SDK_INT >= 19) {// 4.4以上支持
            if (webview != null) {
                webview.evaluateJavascript(trigger, null);
            }
        } else {
            if (webview != null) {
                webview.loadUrl(trigger);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (webview != null && webview.canGoBack()) {
            webview.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

            //这个api仅仅清除自动完成填充的表单数据，并不会清除WebView存储到本地的数据
            webview.clearFormData();

            //清除当前webview访问的历史记录
            //只会webview访问历史记录里的所有记录除了当前访问记录
            webview.clearHistory();

            //清除网页访问留下的缓存
            //由于内核缓存是全局的因此这个方法不仅仅针对webview而是针对整个应用程序.
            webview.clearCache(true);

            ((ViewGroup) webview.getParent()).removeView(webview);
            webview.destroy();
            webview = null;
        }
        super.onDestroy();
    }

    private void callPhone(final String phone) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ConfirmDialog.Builder builder = new ConfirmDialog.Builder(SimpleWebViewActivity.this);
                builder.setContentText(phone.split(":")[1]);
                builder.setPositiveText("呼叫");
                builder.setNegativeText("取消");
                builder.setConfirmListener(new ConfirmDialog.Builder.ConfirmClickListener() {
                    @Override
                    public void click(boolean b) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        if (b) {
                            intentToCall(SimpleWebViewActivity.this, phone);
                        }
                    }
                });
                dialog = builder.create();
                dialog.show();
            }
        });
    }

    /**
     * 直接拨打电话
     */
    public void intentToCall(final Context context, final String phoneNumber) {
        if (context == null || TextUtils.isEmpty(phoneNumber)) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private void showPaySdk(String cashierId, String cashierToken, String cashierEnv, final String callback) {
        LogUtil.i("QianBao+下单@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        final PayResultCallBackBean bean = new PayResultCallBackBean();
        //调起收银台
        //			cashierId = "MjAxNzAzMjAwMDYwMTIwMDAwMDAzMzM1NnwxNDg5OTk5NDA0ODMw";
        //			cashierToken = "8E9D7D515BE03C9A609C4F5410E51BAF";
        QBPaySDK.getInstance().callPaySDK(cashierId, cashierToken, cashierEnv, new PayResultCallBack() {

            @Override
            public void success(String code, String status) {
                bean.setPayState("success");
                bean.setDetail(new PayResultCallBackBean.DetailBean(status, code));
                goJsResultCallbackHttp(callback, 1, "\'" + JsonUtil.toJson(bean) + "\'");
                //                mWv.loadUrl("javascript:" + callback + "('" + JsonUtil.toJson(bean) + "');");
            }

            @Override
            public void paying(String code, String status) {
                //                mWv.loadUrl("javascript:" + callback + "('" + JsonUtil.toJson(bean) + "');");
                bean.setPayState("fail");
                bean.setDetail(new PayResultCallBackBean.DetailBean(status, code));
                goJsResultCallbackHttp(callback, 1, "\'" + JsonUtil.toJson(bean) + "\'");
                //qb_callback_02082907050336349_1528792497718(1,'{"detail":{"result":"支付失败","code":"000002"},"payState":"fail"}');
            }

            @Override
            public void failed(String code, String message) {
                bean.setPayState("fail");
                bean.setDetail(new PayResultCallBackBean.DetailBean(message, code));
                LogUtil.i("javascript:" + callback + "('" + JsonUtil.toJson(bean) + "');");
                if (TextUtils.equals(code, PayCode.NETERROR)) {
                    ToastUtils.showShortToast("网络超时");
                } else if (TextUtils.equals(code, PayCode.PAY_OUT)) {
                    //取消订单
                    goJsResultCallbackHttp(callback, 1, "\'" + JsonUtil.toJson(bean) + "\'");
                    //                    mWv.loadUrl("javascript:" + callback + "('" + JsonUtil.toJson(bean) + "');");
                } else if (TextUtils.equals(code, PayCode.WEIXIN_ING)
                                   || TextUtils.equals(code, PayCode.AILPAY_ING)
                                   || TextUtils.equals(code, PayCode.BHH_ING)) {//处理中
                    //查询订单支付状态
                    goJsResultCallbackHttp(callback, 1, "\'" + JsonUtil.toJson(bean) + "\'");
                    //                    mWv.loadUrl("javascript:" + callback + "('" + JsonUtil.toJson(bean) + "');");
                } else if (TextUtils.equals(code, PayCode.WEIXIN_ERROR)
                                   || TextUtils.equals(code, PayCode.AILPAY_ERROR)
                                   || TextUtils.equals(code, PayCode.BHH_ERROR)) {//支付失败
                    goJsResultCallbackHttp(callback, 1, "\'" + JsonUtil.toJson(bean) + "\'");
                    //                    mWv.loadUrl("javascript:" + callback + "('" + JsonUtil.toJson(bean) + "');");
                } else if (TextUtils.equals(code, PayCode.PAY_NULL)) {//未开通支付工具

                } else {
                    goJsResultCallbackHttp(callback, 1, "\'" + JsonUtil.toJson(bean) + "\'");
                    //                    mWv.loadUrl("javascript:" + callback + "('" + JsonUtil.toJson(bean) + "');");
                }
            }

            @Override
            public void cancel(String s) {
                bean.setPayState("cancel");
                bean.setDetail(new PayResultCallBackBean.DetailBean(s));
                goJsResultCallbackHttp(callback, 1, "\'" + JsonUtil.toJson(bean) + "\'");
                //                mWv.loadUrl("javascript:" + callback + "('" + JsonUtil.toJson(bean) + "');");
            }
        });
    }

}
